package com.pickup.server;

import com.pickup.api.NeteaseApi;
import com.pickup.filter.MusicFilter;
import com.pickup.pojo.MusicPojo;
import com.pickup.server.impl.MusicServerImpl;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class MusicServer implements MusicServerImpl {

    @Autowired
    private NeteaseApi neteaseApi;

    public List<MusicPojo> NeteaseJson(MusicFilter musicFilter) {
        List<MusicPojo> musicInfo = new ArrayList<>();
        JsonObject jsonObject = musicFilter.getJsonMusic();
        JsonArray list = jsonObject.get("result").getAsJsonObject().get("songs").getAsJsonArray();
        for (JsonElement je : list) {
            JsonObject item = je.getAsJsonObject();
            // 歌手名字
            String singer = item.get("ar").getAsJsonArray().get(0).getAsJsonObject().get("name").getAsString();
            // 歌曲名称
            String song = item.get("name").getAsString();
            //专辑
            String album = item.get("al").getAsJsonObject().get("name").getAsString();
            // 歌曲ID
            String id = item.get("id").getAsString();

            if (!musicFilter.NameAndSong(singer, song)){
                continue;
            }

            MusicPojo musicPojo = new MusicPojo();
            // System.out.print(singer + " - " + song + ".mp3  《" + album + "》  ");
            // 获取歌曲链接
            JsonObject link = (JsonObject) new JsonParser().parse(Objects.requireNonNull(NeteaseApi.getLink(id, "320")));
            JsonObject listitem = link.get("data").getAsJsonArray().get(0).getAsJsonObject();
            String url = null;
            try {
                url = listitem.get("url").getAsString();
            } catch (Exception e) {
                url = "https://link.hhtjim.com/163/"+id+".mp3";
                System.out.println("网易云没有这首歌版权");
            }
            musicPojo.setId(id);
            musicPojo.setName(singer);
            musicPojo.setSong(song);
            musicPojo.setAlbum(album);
            musicPojo.setUrl(url);
            musicInfo.add(musicPojo);
        }

        return musicInfo;
    }
}
